package com.company.example;

import com.company.example.service.impl.TestServiceImpl;
import com.company.example.utils.ProxyGeneratorUtils;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * Created by ywl on 2016/12/13.
 */
public class EnhancerDemo {
    public static void main(String[] args) throws Exception{
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(TestServiceImpl.class);
        enhancer.setCallback(new MethodInterceptorImpl());
        TestServiceImpl ts = (TestServiceImpl) enhancer.create();
        ts.a();
        ts.b();
        System.out.println(ts);

        ProxyGeneratorUtils.writeProxyClassToHardDisk("F://EnhancerDemo$$EnhancerByCGLIB$$123.class",
                ProxyGeneratorUtils.getCglibProxyClassBytes(enhancer));

        //System.setProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY, "F://EnhancerDemo$$EnhancerByCGLIB$$123");
    }

    private static class MethodInterceptorImpl implements MethodInterceptor {

        @Override
        public Object intercept(Object obj, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
            System.err.println("Before invoke " + method);
            Object result = methodProxy.invokeSuper(obj, args);
            System.err.println("After invoke " + method);
            return result;
        }
    }


}
